import json
from datetime import datetime

def generate_summary(prediction_data):
    """
    根据预测结果生成摘要信息，与print_summary输出保持一致
    :param prediction_data: 包含预测结果的字典
    :return: 添加了summary字段的prediction_data
    """
    if not prediction_data:
        return prediction_data

    # 获取各部分数据
    stock_info = prediction_data.get("stock_info", {})
    fundamental = prediction_data.get("fundamental_analysis", {})
    technical = prediction_data.get("technical_analysis", {})
    prediction = prediction_data.get("final_prediction", {})

    summary = {
        "stock_info": {
            "name": stock_info.get("name", "未知"),
            "code": stock_info.get("code", "未知")
        },
        "fundamental": {
            "rating": fundamental.get("rating", "无评级"),
            "conclusion": fundamental.get("conclusion", "无结论")
        },
        "technical": {
            "rating": technical.get("rating", "无评级"),
            "conclusion": technical.get("conclusion", "无结论")
        },
        "prediction": {
            "overall_rating": prediction.get("overall_rating", "无评级"),
            "tomorrow_forecast": {
                "direction": prediction.get("tomorrow_forecast", {}).get("预期走势", "不确定"),
                "confidence": prediction.get("tomorrow_forecast", {}).get("置信度", "未知")
            },
            "investment_advice": prediction.get("investment_advice", "无建议"),
            "risk_warning": prediction.get("risk_warning", "无风险提示")
        },
        "generated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }

    # 将摘要添加到原始数据中
    prediction_data["summary"] = summary
    return prediction_data
